<script setup>
import {ref, reactive, watch} from 'vue'
import {useRouter} from 'vue-router'
import {Document, Close} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import TopHeader from './TopHeader.vue'

const router = useRouter()
const isCollapse = ref(false)

// 从 localStorage 获取保存的状态
const savedActiveTab = localStorage.getItem('activeTab')
const savedCollapse = localStorage.getItem('menuCollapse')

// 初始化状态
const activeTab = ref(savedActiveTab || '')
isCollapse.value = savedCollapse === 'true'

// 菜单数据
const menuItems = reactive([
  {
    id: 1,
    title: '系统管理',
    icon: 'Setting',
    children: [
      {id: 11, title: '用户管理', path: '/dynamicmenu/user'},
      {id: 12, title: '角色管理', path: '/dynamicmenu/role'},
      {id: 13, title: '权限管理', path: '/dynamicmenu/permission'}
    ]
  },
  {
    id: 2,
    title: '内容管理',
    icon: 'Document',
    children: [
      {id: 21, title: '文章管理', path: '/dynamicmenu/article'},
      {id: 22, title: '分类管理', path: '/dynamicmenu/category'}
    ]
  },
  {
    id: 3,
    title: '数据统计',
    icon: 'DataLine',
    children: [
      {id: 31, title: '访问统计', path: '/dynamicmenu/visits'},
      {id: 32, title: '用户分析', path: '/dynamicmenu/analysis'},
      {id: 33, title: '育秧数据', path: '/dynamicmenu/seedling-analysis'},
      {id: 34, title: '图片采集', path: '/dynamicmenu/image-crawler'},
      {id: 35, title: '图片列表', path: '/dynamicmenu/image-list-crawler'},
      {id: 36, title: '图片源网址管理', path: '/dynamicmenu/image-src-url'},
      {id: 37, title: '图片列表管理', path: '/dynamicmenu/image-crawler-detail'}
    ]
  },
  {
    id: 5,
    title: '新委托管理',
    icon: 'User',
    children: [
      {id: 51, title: '首页', path: '/entrust/list'},
      {id: 52, title: '发布', path: '/entrust/publish'},
      {id: 53, title: '详情', path: '/entrust/detail'},
      {id: 54, title: '我的', path: '/entrust/profile'}
    ]
  }
])

// 标签页数据
const tabs = ref([])

// 监听标签页变化
watch(activeTab, (newVal) => {
  if (newVal) {
    router.push(newVal)
    // 保存激活的标签页
    localStorage.setItem('activeTab', newVal)
  }
})

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
  // 保存折叠状态
  localStorage.setItem('menuCollapse', isCollapse.value)
}

// 检查路由是否在菜单中
const checkRouteInMenu = (path) => {
  return menuItems.some(menu =>
      menu.children.some(child => child.path === path)
  )
}

// 获取菜单项信息
const getMenuItemInfo = (path) => {
  for (const menu of menuItems) {
    const found = menu.children.find(child => child.path === path)
    if (found) {
      return found
    }
  }
  return null
}

// 初始化标签页
const initTabs = () => {
  const currentPath = router.currentRoute.value.path
  const currentRoute = router.currentRoute.value

  // 如果有保存的标签页，检查是否在菜单中
  if (savedActiveTab) {
    if (checkRouteInMenu(savedActiveTab)) {
      const menuInfo = getMenuItemInfo(savedActiveTab)
      if (menuInfo) {
        const savedTab = {
          title: menuInfo.title,
          path: savedActiveTab
        }
        addTab(savedTab)
        // 确保路由跳转
        router.push(savedActiveTab)
        return
      }
    } else {
      // 如果保存的路径不在菜单中，清空标签页并提示
      closeAllTabs()
      ElMessage.error('当前页面不存在或无权访问')
      return
    }
  }

  // 如果是首页或动态菜单页面，默认打开用户管理
  if (currentPath === '/lz/study' || currentPath === '/dynamicmenu') {
    const defaultPath = '/lz/dynamicmenu/user'
    const menuInfo = getMenuItemInfo(defaultPath)
    if (menuInfo) {
      addTab({
        title: menuInfo.title,
        path: defaultPath
      })
      // 确保路由跳转
      router.push(defaultPath)
    }
  } else {
    // 检查当前路由是否在菜单中
    if (checkRouteInMenu(currentPath)) {
      const menuInfo = getMenuItemInfo(currentPath)
      if (menuInfo) {
        addTab({
          title: menuInfo.title,
          path: currentPath
        })
        // 确保路由跳转
        router.push(currentPath)
      }
    } else {
      // 如果当前路由不在菜单中，清空标签页并提示
      closeAllTabs()
      ElMessage.error('当前页面不存在或无权访问')
    }
  }
}

// 添加标签页
const addTab = (menuItem) => {
  // 如果是父级菜单，不处理
  if (typeof menuItem === 'string' && menuItem.length <= 2) {
    return
  }

  // 如果是子菜单项，获取完整信息
  const menuInfo = typeof menuItem === 'string'
      ? getMenuItemInfo(menuItem)
      : menuItem

  if (!menuInfo) return

  const tabId = menuInfo.path
  if (!tabs.value.some(tab => tab.id === tabId)) {
    tabs.value.push({
      id: tabId,
      title: menuInfo.title,
      path: menuInfo.path
    })
  }
  activeTab.value = tabId
}

// 关闭标签页
const removeTab = (targetId) => {
  let activeIndex = tabs.value.findIndex(tab => tab.id === activeTab.value)
  if (activeTab.value === targetId) {
    tabs.value.splice(activeIndex, 1)
    if (tabs.value.length && activeIndex >= tabs.value.length) {
      activeIndex = tabs.value.length - 1
    }
    activeTab.value = tabs.value[activeIndex]?.id || ''
  } else {
    activeIndex = tabs.value.findIndex(tab => tab.id === targetId)
    tabs.value.splice(activeIndex, 1)
  }
}

// 关闭所有标签页
const closeAllTabs = () => {
  tabs.value = []
  activeTab.value = ''
  localStorage.removeItem('activeTab')
  // 跳转到默认页面
  router.push('/dynamicmenu')
}

// 组件挂载时初始化
initTabs()
</script>

<template>
  <div class="layout-container">
    <!-- 侧边栏菜单 -->
    <div class="menu-container">
      <!-- Logo 区域 -->
      <div class="logo-container">
        <img src="/assets/logo.jpeg" alt="Logo" class="logo-image"/>
        <span :class="{ 'logo-text': true, 'hidden': isCollapse }">管理系统</span>
      </div>
      <el-menu
          class="el-menu-vertical"
          :default-active="activeTab"
          @select="addTab"
          :collapse="isCollapse"
      >
        <template v-for="menu in menuItems" :key="menu.id">
          <el-sub-menu :index="menu.id.toString()">
            <template #title>
              <el-icon>
                <component :is="menu.icon"/>
              </el-icon>
              <span>{{ menu.title }}</span>
            </template>
            <el-menu-item
                v-for="item in menu.children"
                :key="item.id"
                :index="item.path"
            >
              {{ item.title }}
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-container">
      <el-header class="main-header">
        <TopHeader/>
        <!-- 折叠按钮 -->
        <div class="collapse-btn" @click="toggleCollapse">
          <el-icon>
            <component :is="isCollapse ? 'Expand' : 'Fold'"/>
          </el-icon>
        </div>
      </el-header>

      <!-- 标签页 -->
      <div class="tabs-container">
        <el-tabs
            v-model="activeTab"
            type="card"
            closable
            @tab-remove="removeTab"
            class="custom-tabs"
        >
          <el-tab-pane
              v-for="tab in tabs"
              :key="tab.id"
              :label="tab.title"
              :name="tab.id"
          >
          </el-tab-pane>
        </el-tabs>
        <!-- 一键关闭按钮 -->
        <el-button
            v-if="tabs.length > 0"
            type="danger"
            link
            class="close-all-btn"
            @click="closeAllTabs"
        >
          <el-icon>
            <Close/>
          </el-icon>
          关闭所有
        </el-button>
      </div>

      <!-- 内容区域 -->
      <div class="content-container">
        <!-- 无标签页提示 -->
        <div v-if="tabs.length === 0" class="empty-tabs">
          <el-empty description="暂无打开的页面" :image-size="120">
            <template #image>
              <el-icon :size="60" class="empty-icon">
                <Document/>
              </el-icon>
            </template>
            <template #description>
              <p class="empty-text">请从左侧菜单选择要打开的功能</p>
            </template>
          </el-empty>
        </div>

        <!-- 路由视图 -->
        <div v-if="tabs.length > 0" class="router-view-container">
          <router-view></router-view>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.layout-container {
  display: flex;
  height: 100vh;
  background-color: var(--el-bg-color);
}

.menu-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-right: 1px solid var(--el-border-color-light);
  background-color: var(--el-bg-color);
}

.logo-container {
  height: 60px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid var(--el-border-color-light);
}

.logo-image {
  width: 32px;
  height: 32px;
  object-fit: contain;
}

.logo-text {
  margin-left: 8px;
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  transition: opacity 0.3s;
}

.logo-text.hidden {
  opacity: 0;
  width: 0;
  margin-left: 0;
}

.el-menu-vertical {
  flex: 1;
  border-right: none;
  background-color: var(--el-bg-color);
  transition: width 0.3s;
  padding: 8px 0;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 220px;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.main-header {
  padding: 0;
  height: 60px !important;
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.content-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: var(--el-bg-color-page);
  position: relative;
  z-index: 1;
}

:deep(.el-menu-item),
:deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
  font-size: var(--el-font-size-base);
  color: var(--el-text-color-primary);
  margin: 2px 0;
  padding-left: 16px !important;
}

:deep(.el-menu-item:hover),
:deep(.el-sub-menu__title:hover) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

:deep(.el-menu-item.is-active) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  font-weight: 500;
}

:deep(.el-sub-menu .el-menu-item) {
  min-width: 0;
  padding-left: 32px !important;
}

.tabs-container {
  padding: 8px 16px;
  background-color: var(--el-bg-color-page);
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 1;
  margin-top: 8px;
}

.custom-tabs {
  flex: 1;
  margin-right: 16px;
}

.custom-tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 14px;
}

.custom-tabs :deep(.el-tabs__nav) {
  border: none;
  padding: 4px 0;
}

.custom-tabs :deep(.el-tabs__item) {
  height: 32px;
  line-height: 32px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s;
  padding: 0 16px;
  background-color: var(--el-bg-color);
  font-family: 'Microsoft YaHei', '微软雅黑', sans-serif;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

.custom-tabs :deep(.el-tabs__item.is-active) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
  font-weight: 500;
}

.custom-tabs :deep(.el-tabs__item:hover) {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  font-weight: 500;
}

.custom-tabs :deep(.el-tabs__item .el-icon-close) {
  width: 16px;
  height: 16px;
  font-size: 12px;
  margin-left: 4px;
  border-radius: 50%;
  transition: all 0.3s;
  color: var(--el-text-color-secondary);
}

.custom-tabs :deep(.el-tabs__item .el-icon-close:hover) {
  background-color: var(--el-color-danger);
  color: white;
}

.close-all-btn {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  color: var(--el-text-color-regular);
}

.close-all-btn:hover {
  background-color: var(--el-color-danger-light-9);
  border-color: var(--el-color-danger);
  color: var(--el-color-danger);
}

.close-all-btn .el-icon {
  font-size: 14px;
}

.empty-tabs {
  background-color: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
  padding: 40px;
  margin-top: 16px;
  text-align: center;
}

.empty-icon {
  color: var(--el-text-color-secondary);
  margin-bottom: 20px;
}

.empty-text {
  color: var(--el-text-color-secondary);
  font-size: var(--el-font-size-base);
  margin-top: 10px;
}

.router-view-container {
  background-color: var(--el-bg-color);
  padding: 16px;
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow-light);
  min-height: calc(100vh - 160px);
  margin-top: 0;
}

.collapse-btn {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 12;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  cursor: pointer;
  box-shadow: var(--el-box-shadow-light);
  transition: all 0.3s;
  order: 1;
}

.collapse-btn:hover {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

:deep(.el-empty__description) {
  margin-top: 20px;
}

:deep(.el-empty__image) {
  width: 120px;
  height: 120px;
}
</style> 